<?php
require_once 'common/config.php';
require_once 'common/functions.php';
// 检查登录状态
check_login();
// 处理退出登录
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    session_destroy();
    header("Location: login.php");
    exit();
}
$db = db_connect();
// 获取各种统计数据
$stats = [
    'users' => $db->query("SELECT COUNT(*) FROM users")->fetchColumn(),
    'coaches' => $db->query("SELECT COUNT(*) FROM coaches")->fetchColumn(),
    'posts' => $db->query("SELECT COUNT(*) FROM posts")->fetchColumn(),
    'group_courses' => $db->query("SELECT COUNT(*) FROM courses")->fetchColumn(),
    'private_bookings' => $db->query("SELECT COUNT(*) FROM bookings WHERE type = 1")->fetchColumn(),
    'feedback' => $db->query("SELECT COUNT(*) FROM feedbacks WHERE status = 0")->fetchColumn(),
];
// 获取统计分析数据
// 1. 近7天每天的新增用户数
$daily_new_users = $db->query("
    SELECT DATE(created_at) as date, COUNT(*) as count 
    FROM users 
    WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY DATE(created_at)
    ORDER BY date
")->fetchAll(PDO::FETCH_ASSOC);
// 2. 各类型课程预约数量分布
$course_bookings = $db->query("
    SELECT c.name, COUNT(b.id) as booking_count
    FROM courses c
    LEFT JOIN bookings b ON c.id = b.course_id
    GROUP BY c.id
    ORDER BY booking_count DESC
    LIMIT 5
")->fetchAll(PDO::FETCH_ASSOC);
// 3. 反馈类型分布
$feedback_types = $db->query("
    SELECT type, COUNT(*) as count
    FROM feedbacks
    GROUP BY type
")->fetchAll(PDO::FETCH_ASSOC);
// 4. 教练预约排行
$coach_rankings = $db->query("
    SELECT c.name, COUNT(b.id) as booking_count
    FROM coaches c
    LEFT JOIN bookings b ON c.id = b.coach_id
    GROUP BY c.id
    ORDER BY booking_count DESC
    LIMIT 5
")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>控制台 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="../admin/assets/js/jquery.min.js"></script>
</head>
<body>
    <div class="wrapper">
        <?php include 'includes/sidebar.php'; ?>

        <div class="main-content">
            <header class="top-header">
                <div class="header-left">
                    <h2>控制台</h2>
                </div>
                <div class="header-right">
                    <span class="welcome-text">欢迎，<?php 
                        $role_text = $_SESSION['role'] == 1 ? '超级管理员' : '管理员';
                        echo htmlspecialchars($_SESSION['name']) . "（{$role_text}）"; 
                    ?></span>
                    <a href="index.php?action=logout" class="logout-btn">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出</span>
                    </a>
                </div>
            </header>

            <div class="content">
                <!-- 统计卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <i class="fas fa-users"></i>
                        <div class="stat-info">
                            <h3>用户总数</h3>
                            <p><?php echo $stats['users']; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-user-tie"></i>
                        <div class="stat-info">
                            <h3>教练总数</h3>
                            <p><?php echo $stats['coaches']; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-comments"></i>
                        <div class="stat-info">
                            <h3>帖子总数</h3>
                            <p><?php echo $stats['posts']; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-calendar-check"></i>
                        <div class="stat-info">
                            <h3>团课课程</h3>
                            <p><?php echo $stats['group_courses']; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-user-clock"></i>
                        <div class="stat-info">
                            <h3>私教预约</h3>
                            <p><?php echo $stats['private_bookings']; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <i class="fas fa-comment-dots"></i>
                        <div class="stat-info">
                            <h3>待处理反馈</h3>
                            <p><?php echo $stats['feedback']; ?></p>
                        </div>
                    </div>
                </div>

                <!-- 在原有统计卡片后添加统计分析部分 -->
                <div class="analysis-section">
                    <!-- 用户增长趋势 -->
                    <div class="analysis-card">
                        <h3>用户增长趋势（近7天）</h3>
                        <div class="chart-container">
                            <canvas id="userGrowthChart"></canvas>
                        </div>
                    </div>

                    <!-- 课程预约分布 -->
                    <div class="analysis-card">
                        <h3>热门课程排行</h3>
                        <div class="chart-container">
                            <canvas id="courseBookingsChart"></canvas>
                        </div>
                    </div>

                    <!-- 反馈类型分布 -->
                    <div class="analysis-card">
                        <h3>反馈类型分布</h3>
                        <div class="chart-container">
                            <canvas id="feedbackTypesChart"></canvas>
                        </div>
                    </div>

                    <!-- 教练预约排行 -->
                    <div class="analysis-card">
                        <h3>教练预约排行</h3>
                        <div class="chart-container">
                            <canvas id="coachRankingsChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/js/main.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
    // 用户增长趋势图
    const userGrowthCtx = document.getElementById('userGrowthChart').getContext('2d');
    new Chart(userGrowthCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode(array_column($daily_new_users, 'date')); ?>,
            datasets: [{
                label: '新增用户数',
                data: <?php echo json_encode(array_column($daily_new_users, 'count')); ?>,
                borderColor: '#3498db',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 课程预约分布图
    const courseBookingsCtx = document.getElementById('courseBookingsChart').getContext('2d');
    new Chart(courseBookingsCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_column($course_bookings, 'name')); ?>,
            datasets: [{
                label: '预约次数',
                data: <?php echo json_encode(array_column($course_bookings, 'booking_count')); ?>,
                backgroundColor: '#2ecc71'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 反馈类型分布图
    const feedbackTypesCtx = document.getElementById('feedbackTypesChart').getContext('2d');
    new Chart(feedbackTypesCtx, {
        type: 'pie',
        data: {
            labels: ['功能建议', '问题反馈', '其他'],
            datasets: [{
                data: <?php echo json_encode(array_column($feedback_types, 'count')); ?>,
                backgroundColor: ['#3498db', '#e74c3c', '#95a5a6']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false
        }
    });

    // 教练预约排行图
    const coachRankingsCtx = document.getElementById('coachRankingsChart').getContext('2d');
    new Chart(coachRankingsCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode(array_column($coach_rankings, 'name')); ?>,
            datasets: [{
                label: '预约次数',
                data: <?php echo json_encode(array_column($coach_rankings, 'booking_count')); ?>,
                backgroundColor: '#9b59b6'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y'  // 横向柱状图
        }
    });
    </script>

    <style>
    .stats-grid,
    .analysis-section {
        max-width: 1200px;
        margin-left: auto;
        margin-right: auto;
        padding: 0 20px;
    }

    .analysis-section {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        margin-top: 20px;
    }

    .analysis-card {
        background: #fff;
        border-radius: 8px;
        padding: 15px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        min-width: 0;
    }

    .analysis-card h3 {
        margin-bottom: 10px;
        color: #2c3e50;
        font-size: 14px;
    }

    .chart-container {
        height: 250px;
        position: relative;
    }

    @media (max-width: 1024px) {
        .stats-grid,
        .analysis-section {
            grid-template-columns: 1fr;
            padding: 0 15px;
        }
        .chart-container {
            height: 200px;
        }
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: 20px;
    }

    .welcome-text {
        color: black;
        font-size: 14px;
    }

    .logout-btn {
        display: flex;
        align-items: center;
        gap: 5px;
        padding: 6px 12px;
        background-color: #f8f9fa;
        border: 1px solid #ddd;
        border-radius: 4px;
        color: #1E90FF;
        text-decoration: none;
        font-size: 14px;
        transition: all 0.3s ease;
    }

    .logout-btn:hover {
        background-color: #00CED1;
        border-color: #00CED1;
        color: black;
        
    }

    .logout-btn i {
        font-size: 14px;
    }
    </style>
</body>
</html>
